package com.example.uchain.service.impl;

import com.example.uchain.demo.Member;
import com.example.uchain.demo.PageBean;
import com.example.uchain.demo.Result;
import com.example.uchain.demo.dto.MemberCountDTO;
import com.example.uchain.mapper.AuthorMapper;
import com.example.uchain.mapper.MemberMapper;
import com.example.uchain.service.MemberService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MenmberServicelmpl implements MemberService {


    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private AuthorMapper authorMapper;


    //分页查询
    @Override
    public PageBean page(Integer Page, Integer pageSize, String userName, Short sex) {
        //设置分页参数
        PageHelper.startPage(Page, pageSize);

        //执行查询
        List<Member> memberList = memberMapper.findAll(userName, sex);

        // 获取分页信息
        Page<Member> p = (Page<Member>)  memberList;

        //封装pageBean对象
        return new PageBean(p.getTotal(), p.getResult());
    }

    //根据手机号跟密码登录验证
    @Override
    public Member login(Member member) {
        try {
            // 从数据库中获取存储的哈希密码
            String storedHash = memberMapper.getStoredHash(member.getUserName());

            if (storedHash == null) {
                return null;
            }

            // 验证用户输入的密码
            boolean checkpw = BCrypt.checkpw(member.getPassword(), storedHash);

            if (checkpw) {
                // 返回登录信息
                return memberMapper.login(member);
            } else {
               return null;
            }
        } catch (Exception e) {
            // 处理异常并返回null或自定义错误信息
            log.error("登录失败: " + e.getMessage());
            throw new RuntimeException("登录失败", e);
        }
    }


    //添加
    @Override
    public Result AddMem(Member member) {
        log.info("添加用户{}",member);

        //密码加盐 BCrypt加密
        String salt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw(member.getPassword(), salt);
        member.setPassword(hashpw);

        Member member1 = memberMapper.login(member);
        log.info("查询用户{}",member1);
        if (member1 != null){
            log.info("该用户已存在");
            return Result.error("该用户已存在");
        }else {
            memberMapper.AddMem(member);
            return Result.success();
        }
    }

    //删除
    @Override
    public Result  deleteMemById(Integer id) {
        if (memberMapper.findAll1(id) == null){
            log.info("该用户不存在");
            return Result.error("该用户不存在");
        }else {
            memberMapper.deleteMemById(id);
            return Result.success();
        }
    }

    //修改
//@Override
//public Result updateById(Member member) {
//    // 1. 先通过username查询是否存在对应记录
//    Member existingMember = memberMapper.selectByUsername(member.getUserName());
//    if (existingMember == null) {
//        return Result.error("error，username对应的记录不存在");
//    }
//    //    // 2. 检查传入的id是否与查询到的id一致
////    if (!existingMember.getId().equals(member.getId())) {
////        return Result.error("error，id与username对应的信息不匹配，请确认id是否正确");
////    }
//
//    // 3. 执行更新操作
//    if (!memberMapper.updateById(member)) {
//        return Result.error("更新失败，请检查其他约束条件");
//    }
//
//    return Result.success();
//}

@Override
public Result updateById(Member member) {
    // 1. 验证用户存在
    Member existingMember = memberMapper.selectByUsername(member.getUserName());
    if (existingMember == null) {
        return Result.error("用户不存在");
    }

    // 2. 设置正确ID
    member.setId(existingMember.getId());

    // 3. 处理密码更新
    String rawPassword = member.getPassword();
    if (rawPassword != null) {
        // 获取旧密码哈希
        String storedHash = existingMember.getPassword();
        if (storedHash == null) {
            return Result.error("无法获取原始密码哈希");
        }
        // 检查新密码是否与旧密码不同
        if (!BCrypt.checkpw(rawPassword, storedHash)) {
            // 加密新密码
            String salt = BCrypt.gensalt();
            String hashpw = BCrypt.hashpw(rawPassword, salt);
            member.setPassword(hashpw);
        }
    }
//    else {
//        // 移除密码字段，避免覆盖原有哈希
//        member.setPassword(null);
//    }

    // 4. 执行更新
    if (!memberMapper.updateById(member)) {
        return Result.error("更新失败，请检查约束条件");
    }

    return Result.success();
}
    //根据id查找数据
    @Override
    public Member findAll1(Integer id) {
        return  memberMapper.findAll1(id);
    }

    @Override
    public PageBean pageForMem(Integer Page, Integer pageSize, String userName, String id, Integer sign, String phoneNumber, Integer code) {
        //设置分页参数
        PageHelper.startPage(Page, pageSize);

        //执行查询
        List<Member> memberList = memberMapper.findAllWithCode(userName,id,sign,phoneNumber,code);

        // 获取分页信息
        Page<Member> p = (Page<Member>)  memberList;

        //封装pageBean对象
        return new PageBean(p.getTotal(), p.getResult());
    }

    @Override
    public MemberCountDTO memberCount() {
        int totalMemberCount = memberMapper.totalMemberCount(); //总用户数量
        List<Map<String, Object>> dailyAuthorCounts = authorMapper.totalAuthorCountByDay(); //每日总著权人数
        List<Map<String, Object>> newAuthorCountsByDay = authorMapper.newAuthorCountByDay();//每日新增著权人数
        List<Map<String, Object>> totalAuthorCount = getCumulativeCounts(dailyAuthorCounts);

        // 创建一个包含所有信息的 DTO 对象
        MemberCountDTO result = new MemberCountDTO();
        result.setTotalMemberCount(totalMemberCount);
        result.setTotalAuthorCount(totalAuthorCount);
        result.setNewAuthorCount(newAuthorCountsByDay);

        List<Map<String, Object>> totalCount = getMaps(totalAuthorCount, totalMemberCount);
        result.setTotalCount(totalCount);
        return result;
    }

    @NotNull
    private static List<Map<String, Object>> getMaps(List<Map<String, Object>> dailyAuthorCounts, int totalMemberCount) {
        List<Map<String, Object>> totalCount = new ArrayList<>();
        for (Map<String, Object> dayCount : dailyAuthorCounts) {
            // 创建一个新的Map以避免修改原列表
            Map<String, Object> updatedCount = new HashMap<>(dayCount);
            // 获取当前条目的"count"值，如果不存在则默认为0
            Long currentCount = (Long) updatedCount.getOrDefault("cumulative_total", 0L);
            // 将totalMemberCount加到当前条目的"count"上
            updatedCount.put("count", currentCount + totalMemberCount);
            // 将更新后的条目加入到新列表中
            totalCount.add(updatedCount);
        }
        return totalCount;
    }
    @NotNull
    private static List<Map<String, Object>> getCumulativeCounts(List<Map<String, Object>> dailyAuthorCounts) {
        List<Map<String, Object>> resultWithCumulativeCounts = new ArrayList<>();
        long runningTotal = 0L; // 初始化累加计数器

        for (Map<String, Object> dayCount : dailyAuthorCounts) {
            // 创建一个新的Map以包含原有数据并避免修改原列表
            Map<String, Object> updatedCount = new HashMap<>(dayCount);

            // 获取当前条目的"count"值，如果不存在则默认为0
            Long currentCount = (Long) updatedCount.getOrDefault("count", 0L);

            // 更新累加计数器
            runningTotal += currentCount;

            // 在新Map中添加累计计数的字段，例如命名为"cumlative_total"
            updatedCount.put("cumulative_total", runningTotal);

            // 将更新后的条目（含原始计数和累计计数）加入到新列表中
            resultWithCumulativeCounts.add(updatedCount);
        }
        return resultWithCumulativeCounts;
    }
}
